const app = getApp()
import { getPlayerFriends, getHistoryPlayers, addPlayer,addFriend } from '../../../http/game'

Page({
    /**
     * 页面的初始数据
     */
    data: {
        staticUrl: app.globalData.staticUrl,
        searchtext: "",
        players_info: [],
        selectedPlayers: [],
        isHistory: true,
        source: '', //页面来源
        match_billno: '',
    },
    pageData: {
        current_page: 0,
        last_page: 0,
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        console.log(options);
        if (options.type) {
            wx.setNavigationBarTitle({
                title: '我的球友'
            })
            this.setData({
                isHistory: false
            })
        }
        if(options.ismy){
            this.setData({ismy:options.ismy});
        }
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage', (data) => {
            this.setData({
                players_info: data.players_info,
                source: data.source,
                match_billno: data.match_billno,
            });
        });
        this.setData({userInfo:app.globalData.userInfo});
        this.getPlayer();
    },

    inputsearch: function(e) {
        this.setData({ searchtext: e.detail.value });
    },

    async deletplayer(){
        const {selectedPlayers,userInfo} = this.data;

        if(!selectedPlayers || selectedPlayers.length<0){
            return;
        }
        console.log(selectedPlayers);
        var sussuccindex=0;
        for(var index=0;index<selectedPlayers.length;index++){
            const {data} =  await addFriend({player_id:userInfo.player_id,in_player_id:selectedPlayers[index].player_id,type_id:2});
            console.log(data);
            if(data == 1){
                sussuccindex++;
            }
        }
        if(sussuccindex == selectedPlayers.length){ 
            wx.showToast({
              title: '删除好友成功',
            })

            this.getPlayer(1); //刷新
        }
        
    },


    async getPlayer(page = 1) {
        const methods = this.data.isHistory ? getHistoryPlayers : getPlayerFriends
        var userInfo = app.globalData.userInfo;
        
        console.log(app.globalData.userInfo);
    
        let{playerList} = this.data;
        if(page == 1){
            this.pageData.current_page =1
            this.pageData.last_page = 0
            playerList=[];
          
        }
        await methods({player_id:userInfo.player_id, search: this.data.searchtext, page: page }).then(res => {
            const { data } = res
            console.log(data);
            if (data && data.length) data[0].checked = true;
            if(data && data.length>0){
                this.pageData.current_page =this.pageData.current_page +1
                this.pageData.last_page = data.last_page
                if(!playerList || playerList.length<=0){
                this.setData({
                    playerList: data,
                 });
                }
                else{
                    playerList = playerList.concat(data);
                    this.setData({
                        playerList,
                     });
                }
             this.selectedPlayer();
            }
        })
    },
    //选中所有的已经在列表的人
    selectedPlayer() {
        const { playerList, players_info, source } = this.data
        if(playerList && playerList.length>0){
        playerList.forEach((player) => {
            player.disabled = false
            player.checked = false
            players_info.forEach(item => {
                if (player.player_id === item.player_id) {
                    player.disabled = source === 'game' ? true : false
                    player.checked = true
                }
            })
        })
        const selectedPlayers = playerList.filter(item => item.checked === true)
        this.setData({ playerList, selectedPlayers });
      }
    },

    bindPlayerChange: function(e) {
        const { palyer_id, index } = e.currentTarget.dataset
        const { players_info, playerList } = this.data
        playerList[index].checked = !playerList[index].checked
        const selectedPlayers = playerList.filter(item => item.checked === true)
        const deselectedPlayers = playerList.filter(item => item.checked === false)
        this.setData({ playerList, selectedPlayers, deselectedPlayers })
        if (selectedPlayers.length + 1 > 4) {
            wx.showToast({
                title: '同组不能超过4人',
                icon: "error",
            })
            playerList[index].checked = false
            this.setData({ playerList })
            return
        }
    },

    comfirm: function(e) {
        const { selectedPlayers, players_info, deselectedPlayers, source } = this.data
        if (selectedPlayers.length + 1 > 4) {
            wx.showToast({
                title: '同组不能超过4人',
                icon: "error",
            })
            return
        } else {
            const pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
            const prevPage = pages[pages.length - 2];
            const selectedIds = selectedPlayers.map(item => { return item.player_id }) //勾选的id
            const deselectedIds = deselectedPlayers.map(item => { return item.player_id }) //取消勾选的id
            const ids = players_info.map(item => { return item.player_id })
            const selectedId = selectedIds.filter(item => !ids.includes(item))
            if (source === 'game') {
                addPlayer({
                    match_billno: this.data.match_billno,
                    player_ids: selectedId.toString()
                }).then(res => {
                    wx.navigateBack({
                        delta: 1 // 返回上一级页面。
                    })
                    prevPage.getScoring()
                })
            }
            if (source === 'create') {
                let playerArr = players_info.concat(selectedPlayers)
                playerArr = this.unique(playerArr)
                playerArr.forEach((item, index) => {
                    if (deselectedIds.includes(item.player_id)) {
                        playerArr.splice(index, 1)
                    }
                })
                prevPage.setData({ // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
                    players_info: playerArr, // 这里是修改了上一个页面数据:name
                })
                wx.navigateBack({
                    delta: 1 // 返回上一级页面。
                })
            }
        }
    },
    unique(arr) {
        let newArr = [];
        arr.forEach(item => {
            return newArr.filter(e => e.player_id === item.player_id).length > 0 ? '' : newArr.push(item);
        });
        return newArr;
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        const { last_page, current_page } = this.pageData
        if (current_page < last_page) {
            const page = current_page + 1
            this.getdata(page)
        }
    },
})